<template>
	<view>
		<u-upload 
		ref='upload'
		  :action='action' 
	  	:maxSize="5*1024*1024"
		   maxCount="1" 
	 	  :beforeRead='beforeRead' 
			:custom-btn='true' 
			:formData='formData' 
			:afterRead='onSuccess'
			:deletable="false">
			
			<u-avatar :src="vuex_user.avatar_url"  mode="square" size="60" class="u-avatar"></u-avatar>
		</u-upload>
	</view>
</template>

<script>
	let _this = {}
	export default {
		name: "oss-upload",
		data() {
			return {
				action: '',
				formData: {},
				upFileName:'',
			};
		},
		created() {
			_this = this
		},
		methods: {
			//上传之前
			async beforeRead(	file, lists, name) {
				//小程序中this可能会丢失  这个方法是在组件内触发的
				const ossToken = await _this.$u.api.ossToken()
				//设置上传域名
				this.action = ossToken.host
				//文件名 条件编译
				//#ifdef H5
				const fileName = file.name
				//#endif
				//小程序
				//#ifndef H5
				const fileName = file.path
				//#endif
				
				//后缀
				let hz = fileName.slice(fileName.lastIndexOf('.'))
				
				const upFileName = _this.$u.guid(20) + hz
				_this.upFileName = upFileName
				//额外参数
				_this.formData = {
					'key' : upFileName,
					'policy': ossToken.policy,
					'OSSAccessKeyId': ossToken.accessid,
					'success_action_status' : '200', //让服务端返回200,不然，默认会返回204
					'signature': ossToken.signature,
				}
			},
			//上传成功
			 onSuccess(){
				 //console.log(vuex_user.avatar_url)
				setTimeout(async()=>{
					//移除预览区的图片
					// this.$refs.upload.remove(0)
					//请求更新头像
					let name = this.upFileName
					await this.$u.api.updateAvatar({avatar:name})
					//更新缓存
					let resultInfo = await this.$u.api.userInfo()
					this.$u.vuex('vuex_user',resultInfo)
					let lifeData = uni.getStorageSync('lifeData')
					this.userInfo = lifeData['vuex_user']
					this.$u.toast('更新成功')
				},1500)
			}
		}
	}
</script>

<style>

</style>
